package com.tp.controller.system;

import java.util.List;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.tp.base.BaseController;
import com.tp.model.sys.SysUser;
import com.tp.service.AuthService;
import com.tp.service.OrgService;
import com.tp.service.RoleService;
import com.tp.service.UserService;
import com.tp.utils.EncryptionUtil;
import com.tp.utils.StrUtils;
import com.tp.utils.UploadFileUtil;
import com.tp.utils.WebUtils;

/**
 * 用户管理
 * 
 * @author TP
 *
 */
@ControllerBind(controllerKey = "/system/user")
public class UserController extends BaseController {

	private static final String path = "/pages/system/user/user_";

	@Inject
	UserService service;

	@Inject
	OrgService depService;

	@Inject
	RoleService roleService;

	@Inject
	AuthService authService;

	public void index() {
		render(path + "list.html");
	}

	public void list() {
		SysUser model = getModelByAttr(SysUser.class);
		// 排序
		String orderBy = getBaseForm().getOrderBy();
		Page<SysUser> page = service.getPageByWhere(model, orderBy, getPaginator());
		renderCount(page.getTotalRow(), page.getList());
	}

	public void form() {
		int id = getParaToInt("id", 0);
		if (id == 0) {
			SysUser model = new SysUser();
			model.setStatus(1);
			setAttr("model", model);
			setAttr("orgSelect", depService.selectOrg(0));
		} else {
			SysUser model = new SysUser().dao().findById(id);
			setAttr("model", model);
			setAttr("orgSelect", depService.selectOrg(model.getOrgId()));
		}
		render(path + "form.html");
	}

	public void save() {
		SysUser model = getModel(SysUser.class);
		// 修改保存前对用户名做唯一验证
		List<SysUser> sysUsers = model.findByWhere("where logn_acct = ?", model.getStr("logn_acct"));
		// 日志添加
		Integer userid = getUID();
		String now = getNow();
		boolean flag = false;
		if (model.getInt("id") != null && model.getInt("id") > 0) { // 更新
			sysUsers = model.findByWhere("where logn_acct = ? and id != ?", model.get("logn_acct"), model.get("id"));
			if (sysUsers != null && sysUsers.size() > 0) {
				renderFail("保存失败,用户名重复");
				return;
			} else {
				model.put("update_id", userid);
				model.put("update_time", now);
				flag = model.update();
			}
		} else { // 新增
			if (sysUsers != null && sysUsers.size() > 0) {
				renderFail("保存失败,用户名重复");
				return;
			} else {
				model.remove("id");
				model.put("password", WebUtils.passwordEncrypt("123456"));
				model.put("create_id", userid);
				model.put("create_time", now);
				if (StrUtils.empty(model.get("avatar"))) {
					model.setAvatar("\\assets\\images\\default.jpg");
				}
				flag = model.save();
			}
		}
		if (flag) {
			renderOk("保存成功");
		} else {
			renderFail("保存失败");
		}
	}

	@Before(Tx.class)
	public void delete() {
		Integer uid = getUID();
		String[] ids = getPara("ids").split(",");
		boolean flag = service.deleteObject(ids, uid);
		if (flag) {
			renderOk("删除成功");
		} else {
			renderFail("删除失败");
		}
	}
	
	public void restPwd(){
		Integer uid = getUID();
		String[] ids = getPara("ids").split(",");
		boolean flag = service.updataPwd(ids, uid);
		if (flag) {
			renderOk("重置密码成功");
		} else {
			renderFail("重置密码失败");
		}
	}

	public void setRole() {
		int uid = getParaToInt("uId", 0);
		setAttr("roleids", roleService.getUserRoleId(uid));
		setAttr("list", roleService.getRoleList(1));
		render(path + "role.html");
	}

	@Before(Tx.class)
	public void saveRole() {
		int userid = getParaToInt("uId");
		String roleids = getPara("rIds");
		boolean flag = service.saveUserRole(userid, roleids, getUID());
		if (flag) {
			renderOk("设置成功");
		} else {
			renderFail("设置失败");
		}
	}

	public void setAuth() {
		int uid = getParaToInt("uId", 0);
		setAttr("authids", authService.getUserAuthId(uid));
		setAttr("list", authService.getAuthList("F"));
		render(path + "auth.html");
	}

	@Before(Tx.class)
	public void saveAuht() {
		int userid = getParaToInt("uId");
		String authids = getPara("aIds");
		boolean flag = service.saveUserAuth(userid, authids, getUID());
		if (flag) {
			renderOk("设置成功");
		} else {
			renderFail("设置失败");
		}
	}
	
	public void password() {
		render(path + "password.html");
	}
	
	public void modifyPwd(){
		String oldPassword = getPara("oldPassword", "");
		String password = getPara("password", "");
		if (StrUtils.isEmpty(oldPassword) || StrUtils.isEmpty(password)) {
			renderFail("密码不能为空");
			return;
		}
		String encryptPassword = EncryptionUtil.encryptMD5ToString(oldPassword).toLowerCase();
		SysUser user = getSessionUser();
		String md5Password = "";
		String userPassword = user.get("password");
		String decryptPassword = WebUtils.passwordDecrypt(userPassword);
		md5Password = EncryptionUtil.encryptMD5ToString(decryptPassword).toLowerCase();
		if (!md5Password.equals(encryptPassword)) {
			renderFail("密码错误，请您重新输入。");
			return;
		}
		user.setPassword(WebUtils.passwordEncrypt(password));
		// 添加日志
		user.put("update_id", user.getUserId());
		user.put("update_time", getNow());
		boolean flag = user.update();
		if (flag) {
			renderOk("修改密码成功");
		} else {
			renderFail("修改密码失败");
		}
	}

	public void upload() {
		Ret t = UploadFileUtil.UploadFile("file", "avatar", this);
		renderJson(t);
	}
}
